#include "Socket.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"
#include <jsoncpp/json/json.h>
#include <iostream>
#include <string>
#include <ctime>
#include <unistd.h>

int main(int argc, char *args[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ./client -ip -port" << std::endl;
        exit(0);
    }
    std::string ip = args[1];
    uint16_t port = std::stoi(args[2]);

    SockSPtr sockfd = std::make_shared<TcpSocket>();
    if(sockfd->BuildClientSocket(ip, port))
        std::cout<<"Build success"<<std::endl;
    else exit(1);

    srand(time(nullptr));
    const std::string opers = "+-/%*&^$";

    std::string buffer;
    while (1)
    {
        int x = rand() % 10;
        usleep(x * 100);
        int y = rand() % 10;
        usleep(x * y * 10);
        char oper = opers[rand() % opers.size()];

        auto req = Factory::BuildRequestDefault();
        req->SetValue(x, y, oper);

        std::string reqstr;
        req->Serialize(&reqstr);
        reqstr = Encode(reqstr);
        std::cout<<"reqstr: "<<reqstr<<std::endl;

        sockfd->Send(reqstr);
        req->Print();

        while (1)
        {
            ssize_t n = sockfd->Recv(&buffer);
            if(n<=0) 
            {
                std::cout<<"sockfd error"<<std::endl;
                break;
            }
            std::cout<<"buffer: "<<buffer<<std::endl;

            std::string respstr = Decode(buffer);
            if (respstr.empty())
                continue;
            std::cout<<"Decode success: "<<respstr<<std::endl;

            auto resp = Factory::BuildResponseDefault();
            resp->DeSerialize(respstr);
            resp->PrintSult();
            break;
        }
        sleep(5);
    }
    //sockfd->Close();
    return 0;
}